<template>
  <div class="uploaderTop">
    <van-uploader
      :after-read="onRead"
      v-model="fileList"
      multiple
      :max-count="props.count"
      @delete="deleteImg"
    >
      <template #default>
        <div class="uploader flex justify_center align_center flex_column">
          <svg
            class="icon"
            aria-hidden="true"
          >
            <use xlink:href="#icon-shangchuan" />
          </svg>
          <p class="content3 font400 color3">
            上传图片
          </p>
        </div>
      </template>
    </van-uploader>
  </div>
</template>

<script setup lang="ts">
import axios from 'axios'
import { getToken } from '@/service/cookie'
import { ref, onMounted } from 'vue'
const emit = defineEmits(['uploaderImgs', 'detaleImgs'])
const morepic: any = ref([])
const fileList: any = ref([])
const props = defineProps({
  count: {
    type: Number,
    default: 1
  },
  type: {
    type: Number,
    default: 0
  },
  fileList: {
    type: Object,
    default: Array,
    required: true
  }
})

onMounted(() => {
  fileList.value = props.fileList
})

const onRead = async (file: any) => {
  if (file.length > 1) {
    file.forEach(async (item:any) => {
      const formData = new FormData()
      formData.append('file', item.file)
      uploadFile(formData)
    })
  } else {
    const formData = new FormData()
    formData.append('file', file.file)
    uploadFile(formData)
  }
}

const uploadFile = async (formData:any) => {
  axios({
    method: 'post',
    url: import.meta.env.VITE_API_BASEURL + 'v1/common/upload',
    data: formData,
    headers: { 'Content-Type': 'multipart/form-data', authorization: getToken('token') }
  }).then((res:any) => {
    morepic.value.push(res.data.data.url)
    emit('uploaderImgs', morepic.value, props.type)
    morepic.value = []
    // morepic.value.push(res.data.data.url)
  })
}
const deleteImg = (i:any, detail:any) => {
  emit('detaleImgs', detail.index, props.type)
//   form.value.morepic.splice(detail.index, 1)
}
</script>

<style lang="less" scoped>
  .uploaderTop{
    margin:10px 0;
  }
  .uploader {
    width: 75px;
    height: 75px;
    background: #fff;
    // border-radius: 5px;
    text-align: center;
    .icon {
      width: 23px;
      height: 23px;
      margin-bottom: 13px;
    }
  }

  @media (min-width: 750px) {
    .uploaderTop{
    margin:10px 0;
  }
  .uploader {
    width: 75px;
    height: 75px;
    background: #fff;
    // border-radius: 5px;
    text-align: center;
    .icon {
      width: 23px;
      height: 23px;
      margin-bottom: 13px;
    }
  }
}
</style>
